<template>
  <div class="test-page">
    <div class="test-header">
      <h1>🧪 统计功能测试中心</h1>
      <div class="connection-info">
        <div class="status" :class="{ connected: isConnected }">
          <div class="dot"></div>
          <span>{{ isConnected ? '已连接' : '未连接' }}</span>
        </div>
        <button @click="navigateToDashboard" class="dashboard-btn">
          📊 打开实时大屏
        </button>
      </div>
    </div>

    <div class="test-sections">
      <!-- API测试区域 -->
      <div class="test-section">
        <h2>🔗 API接口测试</h2>
        <div class="test-buttons">
          <button @click="testGetDashboardData" class="test-btn primary">
            📊 获取仪表板数据
          </button>
          <button @click="testGetQuantityRatio" class="test-btn info">
            📈 获取数量占比
          </button>
          <button @click="testGetAmountRatio" class="test-btn success">
            💰 获取金额占比
          </button>
          <button @click="testGetInboundRanking" class="test-btn warning">
            🏆 获取入库排名
          </button>
          <button @click="testGetOutboundRanking" class="test-btn danger">
            📤 获取出库排名
          </button>
          <button @click="testGetStatistics" class="test-btn secondary">
            📦 获取出入库统计
          </button>
          <button @click="testGetAlerts" class="test-btn alert">
            ⚠️ 获取库存预警
          </button>
          <button @click="testRefreshAll" class="test-btn refresh">
            🔄 批量刷新数据
          </button>
        </div>
      </div>

      <!-- SignalR测试区域 -->
      <div class="test-section">
        <h2>📡 SignalR推送测试</h2>
        <div class="test-buttons">
          <button @click="testInboundMessage" class="test-btn success">
            📥 模拟入库成功
          </button>
          <button @click="testOutboundMessage" class="test-btn warning">
            📤 模拟出库成功
          </button>
          <button @click="connectSignalR" class="test-btn primary" :disabled="isConnected">
            🔗 连接SignalR
          </button>
          <button @click="disconnectSignalR" class="test-btn danger" :disabled="!isConnected">
            🔌 断开连接
          </button>
        </div>
        <div class="signalr-info">
          <p><strong>连接状态:</strong> {{ isConnected ? '已连接' : '未连接' }}</p>
          <p><strong>连接地址:</strong> http://localhost:5215/InventoryReadHub</p>
          <p><strong>监听事件:</strong> {{ signalrEvents.length }} 个</p>
        </div>
      </div>
    </div>

    <!-- 响应数据显示区域 -->
    <div class="response-section">
      <div class="response-header">
        <h2>📋 API响应数据</h2>
        <div class="response-controls">
          <button @click="clearResponse" class="clear-btn">清空</button>
          <button @click="copyResponse" class="copy-btn">复制</button>
        </div>
      </div>
      <div class="response-content">
        <pre>{{ responseData || '请点击上方按钮测试API接口...' }}</pre>
      </div>
    </div>

    <!-- SignalR消息显示区域 -->
    <div class="messages-section">
      <div class="messages-header">
        <h2>🔔 SignalR实时消息</h2>
        <div class="messages-controls">
          <button @click="clearMessages" class="clear-btn">清空消息</button>
          <span class="message-count">{{ signalrMessages.length }} 条消息</span>
        </div>
      </div>
      <div class="messages-list">
        <div 
          v-for="message in signalrMessages" 
          :key="message.id"
          class="message-item"
          :class="message.type"
        >
          <div class="message-header">
            <span class="message-type">{{ message.type }}</span>
            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="message-content">{{ message.content }}</div>
        </div>
        <div v-if="signalrMessages.length === 0" class="no-messages">
          暂无SignalR消息，请连接后进行测试...
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { signalRService } from '@/services/SignalRService'
import { statisticsService } from '@/services/StatisticsService'

const router = useRouter()
const isConnected = ref(false)
const responseData = ref('')

// SignalR消息
interface SignalRMessage {
  id: string
  type: string
  content: string
  timestamp: Date
}

const signalrMessages = ref<SignalRMessage[]>([])
const signalrEvents = [
  'ReceiveInventoryQuantityRatio',
  'ReceiveInventoryAmountRatio',
  'ReceiveInOutboundStatistics',
  'ReceiveInOutboundRanking',
  'ReceiveDashboardData',
  'ReceiveInboundSuccess',
  'ReceiveOutboundSuccess',
  'ReceiveLowStockAlert'
]

onMounted(async () => {
  await setupSignalR()
})

onUnmounted(() => {
  cleanupSignalR()
})

// 设置SignalR连接
async function setupSignalR() {
  try {
    if (!signalRService.isConnected) {
      await signalRService.start()
    }
    
    isConnected.value = signalRService.isConnected
    
    if (signalRService.connection) {
      // 设置所有消息监听器
      signalrEvents.forEach(eventName => {
        signalRService.connection!.on(eventName, (data) => {
          addSignalRMessage(eventName, JSON.stringify(data, null, 2))
        })
      })
    }
    
    console.log('✅ 测试页面SignalR连接已建立')
  } catch (error) {
    console.error('SignalR连接失败:', error)
    isConnected.value = false
  }
}

// 清理SignalR连接
function cleanupSignalR() {
  if (signalRService.connection) {
    signalrEvents.forEach(eventName => {
      signalRService.connection!.off(eventName)
    })
  }
}

// API测试方法
async function testGetDashboardData() {
  try {
    responseData.value = '正在获取仪表板数据...'
    const result = await statisticsService.getDashboardData()
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function testGetQuantityRatio() {
  try {
    responseData.value = '正在获取库存数量占比...'
    const result = await statisticsService.getGoodsPercentageNumber({ topCount: 10 })
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function testGetAmountRatio() {
  try {
    responseData.value = '正在获取库存金额占比...'
    const result = await statisticsService.getInventoryAmountRatio({ topCount: 10 })
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function testGetInboundRanking() {
  try {
    responseData.value = '正在获取入库排名...'
    const result = await statisticsService.getInOutboundRanking({ 
      isInbound: true, 
      topCount: 10 
    })
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function testGetOutboundRanking() {
  try {
    responseData.value = '正在获取出库排名...'
    const result = await statisticsService.getInOutboundRanking({ 
      isInbound: false, 
      topCount: 10 
    })
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function testGetStatistics() {
  try {
    responseData.value = '正在获取出入库统计...'
    const result = await statisticsService.getInOutboundStatistics({
      startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      endDate: new Date().toISOString().split('T')[0]
    })
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function testGetAlerts() {
  try {
    responseData.value = '正在获取库存预警...'
    const result = await statisticsService.getLowStockAlert()
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function testRefreshAll() {
  try {
    responseData.value = '正在批量刷新所有数据...'
    const result = await statisticsService.refreshAllData()
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

// SignalR测试方法
async function testInboundMessage() {
  try {
    const result = await statisticsService.sendInboundSuccessMessage({
      goodsName: '测试商品A',
      quantity: Math.floor(Math.random() * 100) + 10,
      operatorName: '测试操作员'
    })
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function testOutboundMessage() {
  try {
    const result = await statisticsService.sendOutboundSuccessMessage({
      goodsName: '测试商品B',
      quantity: Math.floor(Math.random() * 50) + 5,
      operatorName: '测试操作员'
    })
    responseData.value = JSON.stringify(result, null, 2)
  } catch (error) {
    responseData.value = `错误: ${error}`
  }
}

async function connectSignalR() {
  try {
    await signalRService.start()
    isConnected.value = signalRService.isConnected
    addSignalRMessage('System', 'SignalR连接成功')
  } catch (error) {
    addSignalRMessage('System', `SignalR连接失败: ${error}`)
  }
}

async function disconnectSignalR() {
  try {
    await signalRService.stop()
    isConnected.value = false
    addSignalRMessage('System', 'SignalR连接已断开')
  } catch (error) {
    addSignalRMessage('System', `断开连接失败: ${error}`)
  }
}

// 工具方法
function addSignalRMessage(type: string, content: string) {
  const message: SignalRMessage = {
    id: Date.now().toString() + Math.random(),
    type,
    content,
    timestamp: new Date()
  }
  
  signalrMessages.value.unshift(message)
  
  // 限制消息数量
  if (signalrMessages.value.length > 50) {
    signalrMessages.value.pop()
  }
}

function clearMessages() {
  signalrMessages.value = []
}

function clearResponse() {
  responseData.value = ''
}

function copyResponse() {
  if (responseData.value) {
    navigator.clipboard.writeText(responseData.value)
    alert('响应数据已复制到剪贴板')
  }
}

function formatTime(date: Date): string {
  return date.toLocaleTimeString('zh-CN')
}

function navigateToDashboard() {
  router.push('/RealtimeStatistics')
}
</script>

<style scoped>
.test-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
  font-family: 'Microsoft YaHei', sans-serif;
}

.test-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  border-radius: 15px;
  padding: 25px;
  margin-bottom: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.test-header h1 {
  margin: 0;
  color: #2c3e50;
  font-size: 2.2em;
}

.connection-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  background: #e74c3c;
  color: white;
  font-weight: 600;
}

.status.connected {
  background: #27ae60;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: currentColor;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.dashboard-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.dashboard-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.test-sections {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 25px;
  margin-bottom: 25px;
}

.test-section {
  background: white;
  border-radius: 15px;
  padding: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.test-section h2 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 1.4em;
  border-bottom: 2px solid #ecf0f1;
  padding-bottom: 10px;
}

.test-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.test-btn {
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.test-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.test-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.test-btn.primary { background: #3498db; color: white; }
.test-btn.success { background: #27ae60; color: white; }
.test-btn.info { background: #17a2b8; color: white; }
.test-btn.warning { background: #f39c12; color: white; }
.test-btn.danger { background: #e74c3c; color: white; }
.test-btn.secondary { background: #6c757d; color: white; }
.test-btn.alert { background: #fd7e14; color: white; }
.test-btn.refresh { background: #6f42c1; color: white; }

.signalr-info {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #17a2b8;
}

.signalr-info p {
  margin: 5px 0;
  font-size: 14px;
}

.response-section,
.messages-section {
  background: white;
  border-radius: 15px;
  padding: 25px;
  margin-bottom: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.response-header,
.messages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 2px solid #ecf0f1;
  padding-bottom: 15px;
}

.response-header h2,
.messages-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.4em;
}

.response-controls,
.messages-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.clear-btn,
.copy-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s ease;
}

.clear-btn:hover,
.copy-btn:hover {
  background: #5a6268;
}

.message-count {
  background: #17a2b8;
  color: white;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.response-content {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.response-content pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #2c3e50;
}

.messages-list {
  max-height: 400px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #17a2b8;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.message-item:hover {
  background: #e9ecef;
  transform: translateX(5px);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.message-type {
  background: #17a2b8;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
}

.message-time {
  font-size: 11px;
  color: #6c757d;
}

.message-content {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  background: white;
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 200px;
  overflow-y: auto;
}

.no-messages {
  text-align: center;
  padding: 40px 20px;
  color: #6c757d;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .test-sections {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .test-page {
    padding: 15px;
  }
  
  .test-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .test-header h1 {
    font-size: 1.8em;
  }
  
  .test-buttons {
    grid-template-columns: 1fr;
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
